<template lang="pug">
.view.cp-invoice-man-purchase.fix-flex-pos
  //- 查询
  el-form.manpur-search(:inline="true")
    el-form-item
      el-select.select-width(v-model="timeType", placeholder="请选择")
        el-option(key="0", label="创建时间", :value="0")
        el-option(key="1", label="提交时间", :value="1")
        el-option(key="2", label="审批时间", :value="2")
        el-option(key="3", label="下单时间", :value="3")
    el-form-item
      el-date-picker.date-width(
        v-model="dateRange",
        type="daterange",
        unlink-panels,
        start-placeholder="开始日期",
        end-placeholder="结束日期",
        value-format="timestamp",
        :default-time="['00:00:00', '23:59:59']")
    el-form-item
      el-input(v-model="orderNo", placeholder="采购订单号", suffix-icon="el-icon-search", style="width: 200px")
    el-form-item(label="状态 :")
      el-select(v-model="orderStatus", placeholder="请选择", style="width: 90px")
        el-option(label="全部", :value="null")
        el-option(v-for="(item, index) in statusSelect", :key="index", :label="item.name", :value="item.value")
    el-form-item(label="供应商 :")
      el-select.select-width(v-model="orderSupply", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(v-for="(item, index) in supplySelect", :key="index", :label="item.name", :value="item.value")
    el-form-item(label="采购员 :")
      el-select.select-width(v-model="orderBuyer", placeholder="请选择")
        el-option(label="全部", :value="null")
        el-option(v-for="(item, index) in empSelect", :key="index", :label="item.name", :value="item.value")
    el-form-item
      el-button(type="primary", @click="search") 搜索
  //- 表格
  .manpur-table
    el-table(
      :data="tableData",
      highlight-current-row,
      v-loading="loadingData",
      @row-click="handleClickRow",
      :row-class-name="tableRowClassName",
      size="mini",
      height="100%")
      el-table-column(align="center", show-overflow-tooltip, type="index", :index="indexMethod", label="序号", :fixed="true")
      el-table-column(align="center", label="采购订单号")
        template(slot-scope="scope")
          el-tooltip(
            effect="dark"
            placement="top"
            :content="scope.row.order")
            div.cell.el-tooltip(style="padding: 0") {{scope.row.order}}
      el-table-column(align="center", show-overflow-tooltip, prop="status", label="订单状态")
        template(slot-scope="scope")
          span {{ scope.row.status | compare-list(statusSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="supply", label="供应商")
        template(slot-scope="scope")
          span {{ scope.row.supply | compare-list(supplySelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="countAll", label="价税合计")
      el-table-column(align="center", show-overflow-tooltip, prop="currency", label="币种")
      el-table-column(align="center", show-overflow-tooltip, prop="creator", label="创建人")
        template(slot-scope="scope")
          span {{ scope.row.creator | compare-list(empSelect) }}
      el-table-column(align="center", show-overflow-tooltip, prop="createTime", label="创建时间")
        template(slot-scope="scope")
          span {{ scope.row.createTime | date-format }}
  //- 分页
  el-pagination.manpur-pagination(
    background,
    layout="total, prev, pager, next, jumper",
    prev-text="上一页",
    next-text="下一页",
    @current-change="handlePageChange",
    :current-page="pageNum",
    :page-size="pageSize",
    :total="totalNum")
  .manpur-side-table(v-loading="loadingDetail")
    .table-title
      span.info 采购订单号：{{formData.orderNo}}
      span.info 供应商：{{formData.supply | compare-list(supplySelect)}}
      span.info 订单总额：{{formData.payAmount}}
      a.init-btn(v-if="!formData.invArray || !formData.invArray.length",
        v-show="isEdit", @click="initInvArray") 初始化
      .btn-wrap
        el-button(size="mini", type="primary", v-show="!isEdit && formData.orderNo", @click="editDetail") 编辑
        el-button(size="mini", type="primary", v-show="isEdit", @click="cancelDetail", plain) 取消
        el-button(size="mini", type="primary", v-show="isEdit", @click="saveDetail") 保存
    el-table.pinv-pop-table(:data="formData.invArray", size="mini", height="160px")
      el-table-column(show-overflow-tooltip, type="index", label="序号")
      el-table-column(show-overflow-tooltip, label="付款金额")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.paymentAmount}}
          el-input(v-show="scope.row.canEdit", v-model="scope.row.paymentAmount")
      el-table-column(show-overflow-tooltip, label="币种")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.currency | compare-list(currencySelect)}}
          el-select(v-show="scope.row.canEdit", v-model="scope.row.currency")
            el-option(v-for="(item, index) in currencySelect", :key="index", :label="item.name", :value="item.value")
      el-table-column(show-overflow-tooltip, label="是否已付款")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.paymentFlag | compare-list(paymentFlagSelect)}}
          el-select(v-show="scope.row.canEdit", v-model="scope.row.paymentFlag")
            el-option(v-for="(item, index) in paymentFlagSelect", :key="index", :label="item.name", :value="item.value")
      el-table-column(label="付款日期", min-width="120px")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.paymentDate | day-format}}
          div.table-input-time(v-show="scope.row.canEdit")
            el-date-picker(v-model="scope.row.paymentDate", type="date")
      el-table-column(show-overflow-tooltip, label="已收发票金额")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.invoiceAmount}}
          el-input(v-show="scope.row.canEdit", v-model="scope.row.invoiceAmount")
      el-table-column(show-overflow-tooltip, label="发票类型")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.invoiceType | compare-list(invoiceTypeSelect)}}
          el-select(v-show="scope.row.canEdit", v-model="scope.row.invoiceType")
            el-option(v-for="(item, index) in invoiceTypeSelect", :key="index", :label="item.name", :value="item.value")
      el-table-column(label="开票日期", min-width="120px")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.invoiceDate | day-format}}
          div.table-input-time(v-show="scope.row.canEdit")
            el-date-picker(v-model="scope.row.invoiceDate", type="date")
      el-table-column(show-overflow-tooltip, label="附件")
        template(slot-scope="scope")
          el-upload(
            :ref="`upload${scope.$index}`"
            v-show="scope.row.canEdit"
            action="https://jsonplaceholder.typicode.com/posts/"
            :limit="1"
            :show-file-list="false"
            :before-upload="uploadFileBefore"
            :on-success="uploadFileSucc"
            :on-error="uploadFileFail")
            i.el-icon-plus(@click="uploadFile(scope.$index)")
          span(v-if="scope.row.attachList && scope.row.attachList.length", v-show="!scope.row.canEdit")
            a(target="_blank", :href="scope.row.attachList[0].url") {{ scope.row.attachList[0].name }}
      el-table-column(label="操作", min-width="104px", fixed="right", v-if="isEdit")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit")
            i.icon-act.el-icon-edit(@click="editInv(scope.$index, scope.row)")
            i.icon-act.el-icon-plus(@click="addInv(scope.$index, scope.row)")
            i.icon-act.el-icon-delete(@click="deleteInv(scope.$index, scope.row)")
          div(v-show="scope.row.canEdit")
            i.icon-act.el-icon-check(@click="saveEditInv(scope.$index, scope.row)")
            i.icon-act.el-icon-close(@click="cancelEditInv(scope.$index, scope.row)")
    .total-info
      span 已付款总额：{{totalPayment}}
      span 已收发票总额：{{totalInvoice}}
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import PurApi from '@/api/purchase';
import InvoiceApi from '@/api/manage/invoice';

export default {
  name: 'invpurchase',
  components: {
  },
  data() {
    return {
      // 表格
      loadingData: true,
      tableData: [],
      pageNum: 1,
      totalNum: 0,
      pageSize: 20,
      // 搜索条件
      timeType: 0,
      dateRange: [],
      orderNo: null,
      orderStatus: null,
      orderSupply: null,
      orderBuyer: null,
      // 当前高亮行
      highLightRow: null,
      // 下面表格
      loadingDetail: false,
      isEdit: false,
      formData: {},
      // 搜索下拉框
      statusSelect: [],
      paymentFlagSelect: [
        { name: '是', value: '1' },
        { name: '否', value: '0' }
      ],
      invoiceTypeSelect: [
        { name: '专票', value: '0' },
        { name: '普票', value: '1' },
        { name: 'N.A.', value: '2' }
      ]
    };
  },
  computed: {
    // 已付款总额
    totalPayment() {
      let num = 0;
      if (this.formData.invArray && this.formData.invArray.length) {
        this.formData.invArray.forEach((item) => {
          // 已付款
          if (item.paymentFlag == '1') {
            const value = Number(item.payAmount);
            if (!isNaN(value)) {
              num += value;
            }
          }
        });
      }
      return num;
    },
    // 已收发票总额
    totalInvoice() {
      let num = 0;
      if (this.formData.invArray && this.formData.invArray.length) {
        this.formData.invArray.forEach((item) => {
          const value = Number(item.invoiceAmount);
          if (!isNaN(value)) {
            num += value;
          }
        });
      }
      return num;
    },
    ...mapGetters({
      empSelect: 'empSelect',
      supplySelect: 'supplySelect',
      currencySelect: 'currencySelect'
    })
  },
  created () {
    // 状态列表
    ComApi.getStatus({ orderType: 'procurementorder' }).then((statusList) => {
      this.statusSelect = statusList;
    });
  },
  mounted() {
    this.loadTableData();
  },
  methods: {
    indexMethod (i) {
      const size = this.pageSize || 20;
      return ((this.pageNum - 1) * size) + (i + 1);
    },
    // 当前行class
    tableRowClassName ({ row }) {
      if (this.highLightRow.order === row.order) {
        return 'focus-row';
      }
      return '';
    },
    filterParams() {
      const params = {
        order: this.orderNo,
        status: this.orderStatus,
        supply: this.orderSupply,
        creator: this.orderBuyer,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      const datePros = [
        ['startCreationTime', 'endCreationTime'],
        ['startSubmissionTime', 'endSubmissionTime'],
        ['startApprovalTime', 'endApprovalTime'],
        ['startOrderTime', 'endOrderTime']
      ];
      if (this.dateRange && this.dateRange.length) {
        params[datePros[this.timeType][0]] = this.dateRange[0];
        params[datePros[this.timeType][1]] = this.dateRange[1];
      }
      for (const key in params) {
        if (params[key] === null || params[key] === '') {
          delete params[key];
        }
      }
      return params;
    },
    // 取得表格数据
    loadTableData() {
      this.loadingData = true;
      const params = this.filterParams();
      PurApi.getPurchaseOrder(params).then((result) => {
        if (!result.status) {
          this.tableData = result.obj.records;
          this.totalNum = result.obj.totalNum;
          // 查询第一条详情
          this.highLightRow = result.obj.records[0];
          this.viewDetail(this.highLightRow);
        } else {
          this.tableData = [];
          this.totalNum = 0;
        }
        this.loadingData = false;
      }).catch((error) => {
        this.loadingData = false;
        console.log(JSON.stringify(error));
      });
    },
    // 搜索
    search() {
      if (this.pageNum !== 1) {
        this.pageNum = 1;
      }
      this.loadTableData();
    },
    // 页码改变
    handlePageChange(pageNum) {
      this.pageNum = pageNum;
      this.loadTableData();
    },
    // 点击一行
    handleClickRow(currentrow) {
      if (this.isEdit) {
        this.$message.error('当前处于编辑状态');
        return;
      }
      this.highLightRow = currentrow;
      this.viewDetail(currentrow);
    },
    // 查看详情
    viewDetail(currentrow) {
      this.loadingDetail = true;
      InvoiceApi.getPurchaseDetail({ orderNo: currentrow.order }).then((res) => {
        if (!res.status) {
          this.formData = {
            orderNo: currentrow.order,
            supply: currentrow.supply,
            payAmount: currentrow.countAll,
            invArray: res.obj
          };
          this.invArrayBC = [...this.formData.invArray];
        } else {
          this.formData = {};
          this.invArrayBC = [];
        }
        this.loadingDetail = false;
        // 保存上传的附件信息
        this.upObj = {};
      }).catch((error) => {
        console.log(JSON.stringify(error));
        this.loadingDetail = false;
      });
    },
    // 编辑
    editDetail() {
      this.isEdit = true;
      this.formDataBC = JSON.parse(JSON.stringify(this.formData));
    },
    // 取消
    cancelDetail() {
      this.isEdit = false;
      this.formData = this.formDataBC;
    },
    // 校验invArray
    validArray() {
      let canSave = true;
      if (!this.formData.invArray || !this.formData.invArray.length) {
        this.$message.error('发票列表不能为空');
        canSave = false;
        return false;
      }
      this.formData.invArray.forEach((item) => {
        if (item.canEdit) {
          this.$message.error('请先确认所填信息');
          canSave = false;
          return false;
        }
      });
      return canSave;
    },
    // 保存
    saveDetail() {
      if (this.saving) {
        return false;
      }
      this.saving = true;
      if (!this.validArray()) {
        this.saving = false;
        return false;
      }
      const orderNo = this.formData.orderNo;
      const params = this.formData.invArray.map(ele => ({ ...ele, orderNo }));
      this.loadingDetail = true;
      InvoiceApi.savePurchase(params).then((res) => {
        if (!res.status) {
          this.$message({ message: '保存成功', type: 'success' });
          this.saving = false;
          this.isEdit = false;
        } else {
          this.$message.error(res.comment || '保存失败');
          this.saving = false;
        }
        this.loadingDetail = false;
      }).catch((error) => {
        this.saving = false;
        console.log(JSON.stringify(error));
        this.loadingDetail = false;
      });
    },
    /* ****** 表格操作  ****** */
    // 初始化
    initInvArray() {
      this.$set(this.formData, 'invArray', [{ canEdit: true, attachList: [] }]);
      this.invArrayBC = [{ canEdit: true, attachList: [] }];
    },
    editInv(index) {
      this.invArrayBC[index] = JSON.parse(JSON.stringify(this.formData.invArray[index]));
      this.$set(this.formData.invArray[index], 'canEdit', true);
    },
    addInv(index) {
      this.formData.invArray.splice((index + 1), 0, { canEdit: true, attachList: [] });
      this.invArrayBC.splice((index + 1), 0, { canEdit: true, attachList: [], fromAdd: true });
    },
    deleteInv(index) {
      this.formData.invArray.splice(index, 1);
      this.invArrayBC.splice(index, 1);
    },
    saveEditInv(index) {
      if (this.upObj[index].fileUrl) {
        const attach = this.formData.invArray[index].attachList[0];
        if (!attach) {
          this.formData.invArray[index].attachList[0] = {};
        }
        this.formData.invArray[index].attachList[0].url = this.upObj[index].fileUrl;
        this.formData.invArray[index].attachList[0].name = this.upObj[index].fileName;
      }
      this.formData.invArray[index].canEdit = false;
    },
    cancelEditInv(index) {
      const cache = Object.assign({}, this.invArrayBC[index], { canEdit: false });
      if (cache.fromAdd) {
        this.formData.invArray.splice(index, 1);
        this.invArrayBC.splice(index, 1);
      } else {
        this.formData.invArray.splice(index, 1, cache);
        this.formData.invArray[index].canEdit = false;
      }
    },
    // 附件上传
    uploadFile (index) {
      this.upIndex = index;
      // 每次上传前清空上次文件
      this.$refs[`upload${index}`].clearFiles();
    },
    uploadFileBefore (file) {
      console.log(file);
      this.loading = this.$loading({
        fullscreen: true,
        text: '努力上传中, 请稍等...',
        background: 'transparent'
      });
    },
    uploadFileSucc (res, file) {
      if (file) {
        if (this.loading) {
          this.loading.close();
        }
        this.$message.success(`${file.name} 上传成功, 点击确认即可查看上传文件`);
        this.upObj[this.upIndex] = {
          fileUrl: file.url,
          fileName: file.name
        };
      }
    },
    uploadFileFail (res, file) {
      if (file) {
        if (this.loading) {
          this.loading.close();
        }
        this.$message.warning(`${file.name} 上传失败, 请稍后再试`);
      }
    }
  }
};
</script>

<style lang="sass">
$SEARCHHEIGHT: 56px
$SELECTWIDTH: 100px
.cp-invoice-man-purchase
  .manpur-search
    height: $SEARCHHEIGHT
    padding: 12px 0 12px 16px
    overflow-x: auto
    overflow-y: hidden
    .select-width
      width: $SELECTWIDTH
    .date-width
      width: 260px
    .el-form-item
      margin-right: 14px
    .el-form-item__label
      margin-left: 6px
      padding-right: 6px
    .el-date-editor .el-range__close-icon
      width: 20px
    .el-form-item--small .el-form-item__content, .el-form-item--small .el-form-item__label
      height: 32px
  .manpur-table
    position: absolute
    top: $SEARCHHEIGHT
    bottom: 262px
    left: 16px
    right: 16px
    overflow-x: hidden
    overflow-y: auto
    &::before
      display: none
    .icon-act
      font-size: 16px
      font-weight: 500
      cursor: pointer
      margin-left: 3px
      margin-right: 3px
      &:hover
        color: #5D9BFB
  .el-table
    th, td
      text-align: center
  .el-table .focus-row td
    background: lightgoldenrodyellow
  .manpur-pagination
    position: absolute
    bottom: 226px
    left: 0
    right: 0
    text-align: center
  .manpur-side-table
    position: absolute
    height: 214px
    bottom: 12px
    left: 16px
    right: 16px
    .table-title
      position: relative
      color: #5D9BFB
      line-height: 20px
      margin-bottom: 4px
      .info
        display: inline-block
        min-width: 180px
        background-color: #e4e6e8
        margin-right: 10px
        padding: 5px 20px
        border-radius: 4px
      .init-btn
        margin-left: 16px
      .btn-wrap
        position: absolute
        width: 160px
        right: 10px
        top: 1px
        text-align: right
    .pinv-pop-table
      .table-input-time
        .el-date-editor.el-input, .el-date-editor.el-input__inner
          width: auto
        .el-input--prefix .el-input__inner
          padding-right: 0
      .icon-act
        font-size: 16px
        font-weight: 500
        padding: 4px
        cursor: pointer
        &:hover
          color: #5D9BFB
      .upload-wrap
        display: inline-block
    .total-info
      height: 20px
      line-height: 20px
      font-size: 16px
      text-align: right
      color: #606266
      span
        margin-left: 24px
</style>
